//
//  MasterViewController.m
//  RestkitDemo
//
//  Created by Liu Shuo on 14-10-9.
//  Copyright (c) 2014年 Liu Shuo. All rights reserved.
//

#import "HomeTableViewController.h"
#import "DetailViewController.h"
#import "Result.h"
#import "BaseCar.h"
#import "DataAccess.h"
#import <RestKit/RestKit.h>
#import "MasterTableViewCell.h"

#define SYSTEM_VERSION ([[UIDevice currentDevice] systemVersion])

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)                                                                     \
    ([SYSTEM_VERSION compare:v options:NSNumericSearch] != NSOrderedAscending)

#define IS_IOS8_OR_ABOVE (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))

@interface HomeTableViewController () {
    NSMutableArray *_objects;
    MasterTableViewCell *_prototypeCell;
}
@end

@implementation HomeTableViewController

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self creatMapping];
    [self requestData];
}

- (void)requestData {
    RKObjectManager *manager = [RKObjectManager sharedManager];

    NSDictionary *parameters = @{ @"pagesize" : @"20", @"categoryid" : @"0", @"pageindex" : @"1" };

    [manager getObjectsAtPath:kRootPath
        parameters:parameters
        success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
          Result *result = [[mappingResult dictionary] objectForKey:[NSNull null]];
          if ([result.Message isEqualToString:@"OK"]) {
              _objects = [[mappingResult dictionary] objectForKey:@"Data"];
              [self.tableView reloadData];
          } else {
              NSLog(@"liu test*******%s___%d__| %@", __FUNCTION__, __LINE__, result.Message);
          }
        }
        failure:^(RKObjectRequestOperation *operation, NSError *error) {
        [self requestData];
          NSLog(@"liu test*******%s___%d__| %@", __FUNCTION__, __LINE__, error.localizedDescription);
        }];
}

- (void)creatMapping {

    RKObjectManager *manager = [RKObjectManager sharedManager];

    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[BaseCar class]];
    [mapping addAttributeMappingsFromArray:
                 @[ @"facetitle", @"content", @"PicCover", @"publishtime", @"filepath", @"summary" ]];
    RKResponseDescriptor *responseDescriptior =
        [RKResponseDescriptor responseDescriptorWithMapping:mapping
                                                     method:RKRequestMethodAny
                                                pathPattern:nil
                                                    keyPath:@"Data"
                                                statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];

    [manager addResponseDescriptor:responseDescriptior];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MasterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    [self configureCell:cell forRowAtIndexPath:indexPath];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (IS_IOS8_OR_ABOVE) {
        return UITableViewAutomaticDimension;
    }

    [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];
    [self.prototypeCell updateConstraintsIfNeeded];
    [self.prototypeCell layoutIfNeeded];

    return [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}

#pragma mark - Configure
- (void)configureCell:(MasterTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseCar *article = _objects[indexPath.row];
    UIImage *image = [UIImage imageNamed:@"汽车.png"];
    [cell.image setImageWithURL:[NSURL URLWithString:article.PicCover] placeholderImage:image];
    cell.title.text = article.facetitle;
    cell.content.text = article.summary;
}

#pragma mark - PrototypeCell
- (MasterTableViewCell *)prototypeCell {
    if (!_prototypeCell) {
        _prototypeCell =
            [self.tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MasterTableViewCell class])];
    }

    return _prototypeCell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView
    commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
     forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_objects removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table
        // view.
    }
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath
 *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        BaseCar *object = _objects[indexPath.row];
        [[segue destinationViewController] setUrlString:object.filepath];
    }
}

@end
